package com.winit.openApi.manager;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.openApi.OpenapiLogUtil;
import com.winit.config.service.IConfigService;
import com.winit.method.mapper.MethodMapper;
import com.winit.method.model.Method;
import com.winit.method.service.MethodService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.winit.config.model.Config;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanglin on 2018/6/7.
 */
@Component
public class OpenApiManager {
    @Autowired
    MethodService methodService;
    @Autowired
    IConfigService configService;
    @Autowired
    MethodMapper methodMapper;
    /**
     * 执行任务刷取openapi数据
     */
    public void initOpenApi(){
        try {
            List<JSONObject> openApis = OpenapiLogUtil.analysis();
            for(JSONObject openapi:openApis){
                String name = openapi.getString("action");
                Map selectMap=new HashMap();
                selectMap.put("type","op");
                selectMap.put("name",name);
                Method oldMethod = methodMapper.findByNameAndUriAndService(selectMap);
                if(null !=oldMethod){
                    continue;
                }
                Method method = new Method();
                method.setName(name);
                Config paramConfig=new Config();
                Map paramMap=new HashMap<>();
                paramMap.put("param",openapi.getJSONObject("entity").toJSONString());
                paramConfig.setKVMap(paramMap);
                configService.saveConfig(paramConfig);
                method.setParamConfigId(paramConfig.getId());

                Config rtnConfig=new Config();
                Map rtnMap=new HashMap();
                rtnMap.put("rtn",openapi.getJSONObject("rtn").toJSONString());
                rtnConfig.setKVMap(rtnMap);
                configService.saveConfig(rtnConfig);
                method.setRtnConfigId(rtnConfig.getId());
                method.setType("op");
                methodService.saveMethod(method);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
